'''
Created on Aug 21, 2010

@author: Administrator
'''
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
import spider
import utility
import models


class DefaultHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write("task page")

class SodexoNodeHandler(utility.TemplateSupportRequestHandler):
    def get(self, id):
        node = models.Shop.get_shop(id)
        related = []
        if node is None:
            logging.info("start parse shop node '%s'" %str(id))
            (name, address, phone, tags , related) = spider.parse_shop_by_id(id)
            if name and address and len(tags) > 0:
                node = models.Shop.add_shop(id, name, address, phone, tags, related)
                if node is None:
                    logging.error("try to add node [%d] has met error."%int(id))
                    self.error(500)
        
        self.generate("task_node.html", {"node": node})

class GMapHandler(utility.TemplateSupportRequestHandler):
    def get(self, id):
        logging.info("start gmap shop node '%s'" %str(id))
        node = models.Shop.get_shop(id)
        if node is None:
            logging.error("could not find node [%d]"%int(id))
            self.error(500)
        if node.location is None:
            (lat, lng) = spider.geocode_address(node.address, id)
            if lat and lng:
                node = node.assign_location(lat, lng)
        self.generate("task_gmap.html", {"node": node})

application = webapp.WSGIApplication([
            (r'/task/node/(\d+)', SodexoNodeHandler),
            (r'/task/gmap/(\d+)', GMapHandler),
            ('/task/.*', DefaultHandler),
            ], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()